#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author: zhangZW
@file: view.py
@time: 2022/11/06
@des: description
"""
from django.contrib import auth
from django.http import JsonResponse
# from apps.users.models import User
from django.shortcuts import render, redirect

from apps.users.models import User


def index(request):
    return render(request, 'index.html')


def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if not all([username, password]):
            return render(request, 'index.html', {'errmsg': '请输入用户名或密码'})
        user = auth.authenticate(username=username, password=password)
        if not user:
            return render(request, 'index.html', {'errmsg': '用户名或密码错误'})
        auth.login(request, user)
        response = redirect('/home/')
        return response
    else:
        return JsonResponse({'code': '1', 'message': f'不支持{request.method}!'})


def logout(request):
    if request.method == 'POST':
        user_id = request.session.get('_auth_user_id')
        is_exists = User.objects.filter(id=user_id).exists()
        if not is_exists:
            return JsonResponse({'code': 201, 'msg': '账户不存在'})
        try:
            request.session.flush()
        except Exception as e:
            return JsonResponse({'code': 501, 'msg': f'未知错误{e}'})
        return JsonResponse({'code': 200, 'msg': '退出成功'})
    else:
        return JsonResponse({'code': '1', 'message': f'不支持{request.method}!'})